package cn.bx.bid.ctrl;

import cn.bx.bid.entity.Page;
import cn.bx.bid.entity.Professor;
import cn.bx.bid.service.ProfessorService;
import cn.bx.bid.util.AjaxResult;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

@Controller
public class ProfesserController {
    @Resource
    ProfessorService professorService;

    //分页
    @GetMapping(value = "professorSearch", produces = "application/json;charset=utf-8")
    @ResponseBody
    public Page<Professor> search(@RequestParam(name = "page", defaultValue = "1") int pageNo, @RequestParam(name = "limit", defaultValue = "10") int limit, @RequestParam(name = "professorname", required = false) String professorname, @RequestParam(name = "mobliephone", required = false) String mobliephone, @RequestParam(name = "id", required = false) String id) {
        Page<Professor> page = professorService.paging(pageNo, limit, professorname, mobliephone, id);
        return page;
    }

    //添加
    @RequestMapping(value = "professoradd", produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult register(HttpServletRequest request, @ModelAttribute("u") Professor professor) {

        int r = this.professorService.add(professor);
        if (r > 0) {
            return AjaxResult.success("注册成功！");
        }
        return AjaxResult.error("注册失败！");
    }

    //批量删除
    @GetMapping(value = "professordel", produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult batchDel(@RequestParam("ids[]") long[] ids) {
        int r = this.professorService.batchDel(ids);
        if (r == 1) {
            return AjaxResult.success("删除成功");
        }
        return AjaxResult.error("删除失败");
    }

    //获得id修改
    @GetMapping(value = "professorGet", produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult toupdate(@RequestParam("id") Long id) {
        Professor professor = this.professorService.get(id);
        return professor != null ? AjaxResult.success("成功获取对象", professor) : AjaxResult.error("获取对象失败");
    }
    //修改
    @PostMapping(value = "professorUpdate",produces = "application/json;charset=utf-8")
    @ResponseBody
    public AjaxResult update(@ModelAttribute("professorUpdate") Professor p){
        int r = this.professorService.update(p);
        return r>0? AjaxResult.success("修改成功"): AjaxResult.error("修改失败");
    }
    //日期转换器
    @InitBinder//从请求到Controller
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
        // true:允许输入空值，false:不能为空值
    }
}
